<template>
  <div class="equipment-inquiry">
    <!-- 采购信息部分 -->
    <div class="info-section">
      <div class="title">{{sjinfo.title}}</div>
      <div class="time">发布时间：{{formatDate(sjinfo.fbsj)}}</div>
      <van-divider style="margin-top:10px;margin-bottom:10px;" />
      <div class="buyer">
        <span style="color:#A399A3;font-size:15px;">采购人：</span>
        <span style="color:black;font-size:15px;">{{sjinfo.cgrname}} {{ (sjinfo.provincename ? '(' + sjinfo.provincename
          : '') + ( sjinfo.cityname ? ' / ' + sjinfo.cityname :'' ) + ( sjinfo.areaname ? ' / ' + sjinfo.areaname :'' )
          + ')'}}</span>
        <!-- 增加已人工核实标志 -->
      </div>
      <div class="buyer">
        <span style="color:#A399A3;font-size:15px;">联系方式：</span>
        <span style="color:#FC0B00;font-size:15px;">{{sjinfo.cgrphone}}</span>
        <van-tag type="success" size="small" style="margin-left: 20px;"
          v-if="sjinfo.rghsbz && sjinfo.rghsbz == '1'">已人工核实</van-tag>
      </div>
      <div class="buyer" v-if="sjinfo.jdsl < sjinfo.zdsl">
        <span style="color:#A399A3;font-size:15px;">商机价格：</span>
        <span style="color:#FC0B00;font-size:15px;">{{ sjinfo.price }}元 / 条</span>
      </div>
      <div style="display: flex; align-items: center;width:100%;margin-top:20px;">
        <van-progress :percentage=" sjinfo.jdsl / sjinfo.zdsl * 100" color="#14C262" :stroke-width="14"
          :show-pivot="false" style="width: 85%;" />
        <span style="margin-left: 10px;width:15%;text-align:center;">{{ sjinfo.jdsl }} / {{sjinfo.zdsl}}</span>
      </div>
      <div class="limit-text">剩余 {{ sjinfo.zdsl-sjinfo.jdsl }} 次接单机会；接单后可见联系方式</div>
      <div class="rownr" v-if="sjinfo.jdsl < sjinfo.zdsl">
        <van-button type="primary" plain style="width: 48%;" @click="handleMd(sjinfo)">买断商机</van-button>
        <van-button type="primary" style="width: 48%;" @click="handleJd(sjinfo)">立即接单</van-button>
      </div>
      <div class="reached-limit" v-else>已达上限</div>
      <van-divider style="margin-top:15px;margin-bottom:5px;" />
      <div class="description">
        {{ sjinfo.content ? sjinfo.content:'' }}
      </div>
      <van-divider style="margin-top:5px;margin-bottom:5px;" />
      <!-- <div class="vip-tip" @click="gotoRechHyinfo">
        <div style="display:flex;flex-direction:column;font-size:14px;">
          <span style="font-size:20px;font-weight:bold;">会员专享,提前3分钟收到提醒</span>
          <span style="padding-top:15px;font-size:15px;">打不通全额退、不需要产品全额退</span>
        </div>
        <van-button type="danger" round size="small" style="margin-top:15px;" >立即开通</van-button>
      </div> -->
    </div>
    <!-- 接单记录部分 -->
    <div class="order-record-section">
      <div class="sub-title">接单记录</div>
      <table>
        <thead>
          <tr>
            <th>接单人</th>
            <th>接单时间</th>
            <th>接单条数</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in orderList" :key="index">
            <td>{{ formatName(item.hyname ? item.hyname:item.wxname) }}</td>
            <td>{{ formatDate(item.jdsj ) }}</td>
            <td>{{ item.jdsl }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- 最新可接单询盘部分 -->
    <div class="new-inquiry-section">
      <div class="sub-title">最新可接单询盘</div>
      <div v-for="(inquiry, index) in inquiryList" :key="index" class="inquiry-item" @click="showNow(inquiry)">
        <div class="rownr">
          <div class="inquiry-title">{{inquiry.title}}</div>
          <span style="positon:absolute;right:10px;color:#999">{{inquiry.time}}</span>
        </div>
        <div class="inquiry-meta">
          <div class="rownr">
            <span style="color:#FC3600;">{{(inquiry.provincename ? inquiry.provincename : '') + (inquiry.cityname ? ' /
              ' + inquiry.cityname : '') + (inquiry.areaname ? ' / ' + inquiry.areaname : '' ) }}</span>
            <span style="positon:absolute;right:10px;color:#FC3600;">{{inquiry.jdsl + ' / ' + inquiry.zdsl }}</span>
          </div>
        </div>
      </div>
      <div style="width:100%;color:#7E91E9;text-align:center;" @click="loadMore" v-if="jzgdshow">点击加载更多</div>
    </div>
    <van-dialog v-model:show="showConfirmDialog" :show-confirm-button="false" :show-cancel-button="false"
      :cancel-button-text="取消" :close-on-click-overlay="true">
      <div class="order-page">
        <!-- 商机价格和余额信息 -->
        <div class="info-section">
          <span>商机价格：{{price}}，余额：{{ zhye }}</span>
        </div>
        <!-- 充值部分 -->
        <div class="recharge-section" v-if="czbz == '1' ">
          <span style="width:15%;">充值：</span>
          <van-field style="width:85%; border: 1px solid #e4e7ed; box-sizing: border-box;" v-model="czje" size="small"
            :border="true" type="number" placeholder="请输入充值金额" />
        </div>
        <!-- 接单按钮 -->
        <div class="order-button-section">
          <van-button type="primary" block large @click="doPay">立即接单</van-button>
        </div>
        <!-- 提示信息 -->
        <div class="tip-section">
          <div style="margin-bottom:10px;font-size:15px;">充值后立即接单，余额存入账户</div>
          <div style="padding-bottom:10px;font-size:15px;">信息真实有效，无效全额退款</div>
          <span style="padding-bottom:10px;font-size:15px;">充值即代表您同意</span>
          <van-link type="primary" underline style="color:blue;font-size:15px;" @click="gotoYhxy">《用户服务协议》</van-link>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import wx from 'weixin-js-sdk';
import { addHyinfo, addOrderinfo, getAccessToken, getShareparam, getUserInfo, queryHyinfoByOpenid, queryOrderinfoList, querySjinfo, querySjinfoList, saveOrderinfo } from '../../api/api';
import { floatMul, floatSub } from '../../utils/NumberUtil';
import wechat from '../../utils/wechat';
export default {
  data() {
    return {
      showConfirmDialog: false,
      orderRecords: [],
      orderList: [],
      newInquiries: [],
      sjid: undefined,
      sjinfo: {},
      czje: 200,
      confirmLoading: false,
      price: 0,
      pageNum: 1,
      pageSize: 10,
      hyid: undefined,
      orderinfoList: [],
      inquiryList: [],
      jzgdshow: true,
      jdsl:'',
      mdbz:'0',
      baseurl:'',
      zhye:'0',
      czbz:'0',
      share_config:{}
    }
  },
  created() {
    let that = this // 添加了空格
    this.sjid = this.$route.query.sjid
    this.baseurl = window.location.href
    let openid = localStorage.getItem('openid')
    if(!openid){
      that.getWxopenid()
      //that.querySjinfoBySjid()
    }else{
      that.openid = openid
      that.queryHyinfoByOpenid()
    }
    this.queryOrderinfoList()
    this.querySjinfoList()
    
  },
  mounted() {

  },
  methods: {
    initShareInfo(){
      console.log('initShareInfo',that.share_config)
      wx.onMenuShareAppMessage(that.share_config); // 微信好友
    },
    initShareInfo(){
      let that = this
      //对url进行编码
      var localUrl = window.location.href.split('#')[0];
      console.log('localUrl',localUrl)
      //url传到后台格式
      //这几个参数都是后台从微信公众平台获取到的
      var nonceStr, signature, timestamp, appId, shareUrl;
      let param = {
        url: localUrl
      }
      getShareparam(param).then(res => {
        if(res.code == 200){
          nonceStr = res.data.nonceStr;
          signature = res.data.signature;
          timestamp = res.data.timestamp;
          appId = res.data.appId;
          shareUrl = res.data.url;
          //微信分享配置
          wx.config({
            debug: false,
            appId: appId,
            timestamp: timestamp,      // 需与后台相同
            nonceStr: nonceStr, // 需与后台相同
            signature: signature, // 需与后台相同,
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
          })

          //配置自定义分享内容
          that.share_config = {
                //'imgUrl': 'https://www.xxxxxx.cn/cecerecruit/img/%E6%B5%8B%E6%B5%8B%E6%8B%9B%E5%8B%9F.png', // 这里是需要展示的图标
                'desc': this.sjinfo.content, // 这是分享展示的摘要
                    'title': this.sjinfo.title, // 这是分享展示卡片的标题
                    'link': shareUrl, // 这里是分享的网址
                    'success': function(rr) {
                        //console.log('成功' + JSON.stringify(rr))
                    },
                    'cancel': function(tt) {
                        //console.log('失败' + JSON.stringify(tt));
                    }
            };
            wx.ready(function() {
                wx.onMenuShareAppMessage(that.share_config); // 微信好友
                wx.onMenuShareTimeline(that.share_config); // 微信朋友圈
                wx.onMenuShareQQ(that.share_config); // QQ
            });
        }
      })

    },
    showNow(item){
      window.location.href = "https://sqeybusiness.abcsale.cn/home?" + '?sjid=' + item.sjid
    },
    doPay(){
      let that = this
      if(!that.hyid){
        that.$toast('请先登录')
        return
      }
      if(!that.price){
        that.$toast('商机金额不能为空')
        return
      }
      if(that.zhye < that.price && !that.czje ){
        that.$toast('金额不足')
        return
      }

      if(that.czje){
        that.czbz = '1'
      }else{
        that.czbz = '0'
      }

      if(!that.sjid){
        that.$toast('商机id不能为空')
        return
      }
      let param = {
        sjid: this.sjid,
        hyid: this.hyid,
        jdsl: this.jdsl,
        jdsj: new Date(),
        price: this.price,
        czje: this.czje,
        mdbz: this.mdbz,
        callbackurl:window.location.href,
        czbz:this.czbz 
      }

      if(this.czbz == '1'){
        saveOrderinfo(param).then(res => {
          if(res.code == 200){
            that.$toast('接单成功')
            that.showConfirmDialog = false
            let payurl = res.data.contenturl
            // 假设 payurl 是一个 JSON 字符串，将其转换为 JSON 对象
            let payObj = JSON.parse(payurl);
            payObj.appId = 'wxd81a6bd295facda3'
            // 调起微信支付
            WeixinJSBridge.invoke(
              'getBrandWCPayRequest', 
              payObj,
              function(res){
                if(res.err_msg == "get_brand_wcpay_request:ok" ){
                  // 使用以上方式判断前端返回,微信团队郑重提示：
                  // res.err_msg将在用户支付成功后返回get_brand_wcpay_request:ok，但并不保证它绝对可靠。
                  window.location.href = this.baseurl
                  // 可以在这里添加支付成功后的逻辑，例如更新订单状态等
                  setTimeout(() => {
                    that.querySjinfoBySjid()
                  }, 200);
                } else {
                  that.$toast(res.msg)
                } 
              }
            );
          }else{
            that.$toast(res.msg)
          }
        })
      }else{
        addOrderinfo(param).then(res => {
          debugger
          if(res.code == 200){
            that.$toast('接单成功')
            that.showConfirmDialog = false
            that.zhye = res.data.zhye 
            that.querySjinfoBySjid()
            that.queryOrderinfoList()
          }else{
            that.$toast('接单失败')
          }
        })
      }
      
    },

    getWxopenid(){
      let that = this
      wechat.getOpenId().then(data => {
          let code = data.code
          if (code) {
            try {
              let param = {
                code: code,
              }
              getAccessToken(param).then(res => {
                if(res.code == 200){
                  let access_token = res.data.access_token
                  let openid = res.data.openid
                  that.openid = openid
                  that.accessToken = access_token
                  localStorage.setItem('openid', res.data.openid)
                  let data2 = {
                    openid: openid,
                    access_token: access_token
                  }
                  getUserInfo(data2).then(res1 => {
                    if(res1.code == 200){
                      data2 = res1.data
                      that.saveHyinfoByOpenid(data2);
                    }
                  })
                }
              })
            } catch (error) {
              console.error('获取失败:', error);
            }
          }
      })
      .catch(error => {
        debugger
        console.error('获取失败:', error)
      })
    },

    // 保存会员信息
    saveHyinfoByOpenid(param){
      let that = this
      param.wxname = param.nickname
      addHyinfo(param).then(response => {
        if(response.code == 200){           
          that.hyid = response.data.hyid
          that.zhye = response.data.zhye
          localStorage.setItem('wxname', response.data.wxname)
          localStorage.setItem('hyid', that.hyid)
          localStorage.setItem('headimgurl', that.headimgurl)
        }else{
          console.log('添加失败:', response)
        }
      })
    },

    queryHyinfoByOpenid(){
      let that = this 
      let param = {openid:this.openid}
      queryHyinfoByOpenid(param).then(response => {
        if(response.code == 200){
          if(response.data){
            that.hyid = response.data.hyid
            that.zhye = response.data.zhye
            localStorage.setItem('hyid', that.hyid)
            localStorage.setItem('wxname', response.data.wxname)
            localStorage.setItem('headimgurl', that.headimgurl)
            that.querySjinfoBySjid()
          }else{
            that.getWxopenid()
          }
        }
      })
    },

    queryOrderinfoList() {
      const param = {
        sjid:this.sjid,
        zfzt:'1'
      }
      queryOrderinfoList(param).then(res => {
        if (res.code == 200) {
          this.orderList = res.rows
        }
      })
    },
    gotoYhxy() {
      this.$router.push({
        path: '/xieyi'
      })
    },
    confirmLoading() {
      return this.confirmLoading
    },
    handleJd(sjinfo) { // 添加了空格
      this.price = sjinfo.price
      this.jdsl = 1
      this.showConfirmDialog = true
      this.mdbz = '0'
      this.czje = sjinfo.price 
      if(this.zhye >= this.price){
        this.czbz = '0'
        this.czje = 0 
      }else{
        this.czbz = '1'
        this.czje = price 
      }
    },
    handleMd(sjinfo) { // 添加了空格
      // 这里可以根据需要使用 sjinfo 变量，例如打印日志
      this.price = floatMul(sjinfo.price, floatSub(sjinfo.zdsl, sjinfo.jdsl))
      this.jdsl = floatSub(sjinfo.zdsl, sjinfo.jdsl)
      this.showConfirmDialog = true
      this.mdbz = '1'
      this.czje = this.price 
      if(this.zhye >= this.price){
        this.czbz = '0'
        this.czje = 0
      }else{
        this.czbz = '1'
        this.czje = this.price
      }
    },
    padZero(num) {
      return num.toString().padStart(2, '0')
    },
    formatName(name) {
      if (name.length > 1) {
        return name.substring(0, 1) + '**'
      } else {
        return name
      }
    },
    formatDate(dateStr) {
      const date = new Date(dateStr)
      const now = new Date()
      // 判断是否为今天
      if (date.getDate() === now.getDate() &&
        date.getMonth() === now.getMonth() &&
        date.getFullYear() === now.getFullYear()) {
        // 今天显示时分
        return `今天 ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`
      }
      // 非今天显示完整日期
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} 
              ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`
    },
    querySjinfoBySjid() {
      const param = {
        sjid: this.sjid,
        hyid: this.hyid
      }
      querySjinfo(param).then(res => {
        if (res.code == 200) {
          this.sjinfo = res.data
          this.initShareInfo()
        }
      })
    },

    querySjinfoList() {
      const that = this
      const param = { pageNum: this.pageNum, pageSize: this.pageSize }
      querySjinfoList(param).then((res) => {
        if (res.code === 200) {
          const list = res.rows
          if (list.length > 0) {
            this.inquiryList = list
          }
        }
      }).catch((error) => {
        console.error('查询数据失败:', error)
      })
    },

    loadMore() { // 添加了空格
      this.pageNum++
      const param = { pageNum: this.pageNum, pageSize: this.pageSize }
      querySjinfoList(param).then((res) => {
        if (res.code === 200) {
          const list = res.rows
          if (list.length > 0) {
            this.inquiryList = this.pageNum == 1 ? res.rows : this.inquiryList.concat(res.rows)
          } else {
            this.jzgdshow = false
          }
        }
      }).catch((error) => {
        console.error('查询数据失败:', error)
      })
    },

    gotoRechHyinfo() {
      this.$router.push({ path: '/rechargehy', query: { hyid: this.hyid, zhye: this.zhye }})
    }
  }
}
</script>

<style scoped>

.order-page {
  padding: 5px;
  text-align: center;
}
.info-section {
  padding:10px;
  margin-bottom: 20px;
  border-bottom: #e4e7ed 1px solid;
  padding-bottom: 10px;;
  font-size: 15px;
}

.recharge-section {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  width:100%;
  font-size:15px;
}
.order-button-section {
  margin-bottom: 20px;
  margin-top: 20px;
}
.tip-section {
  color: #999;
  margin-bottom: 10px;
  font-size: 15px;
}
.agreement-section {
  color: #999;
  font-size: 15px;
}
.equipment-inquiry {
  background-color: #ffffff;
  padding:10px;
}
.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}
.time{
  color: #b1b1b1;
  font-size:12px;
}
.buyer{
  margin-bottom: 10px;
}
.contact {
  margin-bottom: 5px;
}
.progress-text {
  float: right;
}
.limit-text {
  color: #999;
  margin-top: 5px;
  font-size: 13px;
}

.rownr {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  flex-direction: row;
  align-items: center;
}
.reached-limit {
  background-color: #e6f7ff;
  color: #1989fa;
  text-align: center;
  padding: 8px;
  border-radius: 4px;
  margin-top: 10px;
}
.description {
  padding: 5px;
  margin-top: 5px;
  line-height: 1.5;
  font-size: 14px;
}
.button-group {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
}
.vip-tip {
  background-color: #ff4949;
  color: white;
  text-align: center;
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;;
}
.sub-title {
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  margin-bottom: 10px;
  color: #FC3600;
  border-bottom: 1px solid #FC3600;
  padding-bottom: 5px;
}
.inquiry-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}
.inquiry-title {
  font-size: 16px;
  margin-bottom: 5px;
  width: 80%;
  overflow: hidden;
}
.inquiry-meta {
  color: #999;
}

table {
  border-collapse: collapse;
  width: 100%;
}

table,
th,
td {
  border: 1px solid #ccc;
  text-align: center;
}

th,
td {
  padding: 8px;
  text-align: center;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}
</style>
